package org.usmile.algorithms.leetcode.simple;

/**
 * 14. 最长公共前缀
 *
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 *
 * 示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 *
 * 示例 2：
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * 提示：
 * 1 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 仅由小写英文字母组成
 */
public class _0014 {
}

class _0014_Solution {
    public String longestCommonPrefix(String[] strs) {
        return lcp(strs, 0, strs.length - 1);
    }

    private String lcp(String[] strs, int left, int right) {
        if (left == right) {
            return strs[left];
        }

        int mid = left + (right - left) / 2;
        String leftLcp = lcp(strs, left, mid);
        String rightLcp = lcp(strs, mid + 1, right);

        return merge(leftLcp, rightLcp);
    }


    private String merge(String str1, String str2) {
        int maxLen = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < maxLen && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }

        return str1.substring(0, index);
    }
}

class _0014_Solution1 {
    public String longestCommonPrefix(String[] strs) {
        int i = 0;
        loop:
        while (true) {
            if (i >= strs[0].length()) {
                break;
            }
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length()) {
                    break loop;
                }
                if (strs[j].charAt(i) != c) {
                    break loop;
                }
            }
            i++;
        }

        return strs[0].substring(0, i);
    }
}